#coding=utf-8
'''
Created on 2013-9-8

@author: Ben

战斗管理
'''

from ..common import BasicThread, Logger, AIConfig
from ..general import GeneralData, GeneralVO
from ..role import FunctionData
import War
import WarData
import time

warManager = None
battlePermitRequest = None
warGetInfoRequest = None

def battlePermitCheck():
    return not WarData.inBattle

def battlePermitCallback():
    WarData.inBattle = True

def warGetInfoCheck():
    return not WarData.haveBattleInfo

def warGetInfoCallback():
    WarData.haveBattleInfo = True
    Logger.log('当前免费借兵次数:' + str(WarData.freePhantomCount), output = True)
    #借兵
    while 0 < WarData.freePhantomCount >= AIConfig.phantom_start_times :
        WarData.freePhantomCount -= 1
        War.phantom()
        time.sleep(0.2)

def start():
    global warManager
    global battlePermitRequest
    global warGetInfoRequest
    if warManager == None:
        warManager = WarManager(name="warManager")
    battlePermitRequest = War.WarBattlePermitRequest(battlePermitCheck, battlePermitCallback, 0, 0)
    warGetInfoRequest = War.WarGetInfoRequest(warGetInfoCheck, warGetInfoCallback, 0, 0)
    warManager.startThread()
    
def pause():
    global warManager
    if warManager != None:
        warManager.pauseThread()

class WarManager(BasicThread.BasicThread):
    
    def callback(self):
        time.sleep(10)
        #判断世界是否开放
        if FunctionData.func10 == 0:
            return
        #获取太史慈的武将id
        generalId = GeneralData.getGeneralIdByPic("zhoutai")
        if generalId <= 0:
            return
        #获取对应的武将数据
        generalVO = GeneralData.getGeneralVO(generalId)
        #判断武将是否在战斗状态
        if generalVO.generalState != GeneralVO.GENERAL_STATE_WAR:
            WarData.inBattle = False
            WarData.haveBattleInfo = False
            return
        
        #获取武将所在战场id
        global battlePermitRequest
        battlePermitRequest.setParams(generalId)
        if battlePermitRequest.run():
            return
        
        #获取战斗信息
        global warGetInfoRequest
        warGetInfoRequest.setParams(generalId)
        if warGetInfoRequest.run():
            return